package com.its.us.sk.server.tcp;

import com.its.us.sk.server.tcp.code.DeCodeInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 接收的是tcp协议的
 * @Author: master
 * @Date: 2020/11/25 14:01
 * @Version: 1.0
 */
@Slf4j
public class NettyTcpServer {
    private final int port;


    public NettyTcpServer(int port) {
        this.port = port;
    }

    /**
     * 服务启动
     */
    public void start() throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            // 绑定线程池
            sb.group(boss, work)
                    // 服务端通道类型
                    .channel(NioServerSocketChannel.class)
                    // 增加一个日志处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    // buf
                    .childHandler(new DeCodeInitializer())
                    // 服务端接受连接的队列长度，如果队列已满，客户端连接将被拒绝
                    .option(ChannelOption.SO_BACKLOG, 1024);
                    // 保持长连接，2小时无数据激活心跳机制
                    //.childOption(ChannelOption.SO_KEEPALIVE, true);
            // 启动服务器
            ChannelFuture cf = sb.bind(port).sync();
            log.info("port is 5004,tcp server is start...");
            System.err.println("port is 5004,tcp server is start...");
            cf.channel().closeFuture().sync(); // 关闭服务器通道
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放线程池资源
            boss.shutdownGracefully().sync();
            work.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) {
        try {
            new NettyTcpServer(5004).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
